package fts_test.lib;

import java.io.RandomAccessFile;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.concurrent.atomic.*;


public class fileReader {

    private static int threadCount = 8;

    public static int search(final int count, final String keywords, final Exe exe) throws Exception {
        AtomicInteger ai = new AtomicInteger(0);
        ExecutorService pool = Executors.newFixedThreadPool(threadCount);

        for (int i = 0; i < count; i++) {
            pool.execute(() -> {
                try {
                    ai.addAndGet(exe.run(keywords));
                } catch (Exception ex) {
                    Logger.getLogger(fileReader.class.getName()).log(Level.SEVERE, null, ex);
                }
            });
        }
        pool.shutdown();
        pool.awaitTermination(1, TimeUnit.DAYS);
        return ai.get();
    }

    public static String[] read(String book, final Exe exe) throws Exception {

        RandomAccessFile rf = new RandomAccessFile(book, "r");
        byte[] bs = new byte[(int) rf.length()];
        rf.readFully(bs);

        String[] ts = new String(bs).split("。");
        if (exe == null) {
            return ts;
        }
        rf.close();

        ExecutorService pool = Executors.newFixedThreadPool(threadCount);

        for (String text : ts) {
            pool.execute(() -> {
                try {
                    exe.run(text);
                } catch (Exception ex) {
                    Logger.getLogger(fileReader.class.getName()).log(Level.SEVERE, null, ex);
                }
            });
        }

        pool.shutdown();
        pool.awaitTermination(1, TimeUnit.DAYS);

        return ts;
    }

    public static interface Exe {

        public int run(String text) throws Exception;
    }
}
